<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设置下拉框中的默认随机选中项，自己书写结构和js</title>
</head>
<body>
    <form action="" method="get">
        年龄:<select name="age" id="ages"></select>
        <input id="random_bom" type="button" value="随机">
    </form>
    <script>
        let ages = document.getElementById("ages");
        let random = document.getElementById("random_bom");
        let age_options = []; // 创建空年龄选项数组
        for(let min_age = 18,i = 0;min_age <= 90;min_age++,i++){
            let option = document.createElement("option");
            option.innerText = `${min_age}岁`;
            option.value = min_age.toString();
            age_options[i] = option;
            ages.appendChild(age_options[i]);
        } // 创建年龄选项18 - 90岁
        random.onclick = function(){
            age_options[Math.floor(Math.random()*age_options.length)].selected = true;
        };
        
    </script>
</body>
</html>